import React, { Component } from 'react';
import { Route, withRouter } from 'react-router-dom';
import { matchRoutes } from 'react-router-config';

const loadBranchData = (routes, location) => {
  const branch = matchRoutes(routes, location.pathname);
  const promises = branch.map(({ route, match }) =>
    route.loadData ? route.loadData(match) : Promise.resolve(null)
  );

  return Promise.all(promises);
};

class PendingNavDataLoader extends Component {
  state = {
    previousLocation: null
  };

  componentWillReceiveProps(nextProps) {
    const { location } = this.props;
    const navigated = nextProps.location !== location;
    const { routes } = this.props;

    if (navigated) {
      // save the location so we can render the old screen
      this.setState({
        previousLocation: location
      });

      // load data while the old screen remains
      loadBranchData(routes, nextProps.location).then(data => {
        // putTheDataSomewhereRoutesCanFindIt(data)
        // clear previousLocation so the next screen renders
        this.setState({
          previousLocation: null
        });
      });
    }
  }

  render() {
    const { children, location } = this.props;
    const { previousLocation } = this.state;

    // use a controlled <Route> to trick all descendants into
    // rendering the old location
    return <Route location={previousLocation || location} render={() => children} />;
  }
}

// wrap in withRouter
export default withRouter(PendingNavDataLoader);
